﻿using JWTWebApi.Models;
using JWTWebApi.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace JWTWebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<LoginController> _logger;

        public LoginController(IConfiguration configuration, ILogger<LoginController> logger)
        {
            _configuration = configuration;
            _logger = logger;
        }

        [HttpPost]
        public IActionResult GetJwtToken(LoginModel login)
        {
            _logger.LogInformation("开始处理JWT Token获取请求，用户名: {UserName}", login?.UserName ?? "未提供");
            
            try
            {
                // 1. 验证用户名密码（此处需替换为实际验证逻辑）
                if (String.IsNullOrEmpty(login.UserName))
                {
                    _logger.LogWarning("JWT Token获取失败：用户名为空或未提供");
                    return Unauthorized();
                }

                _logger.LogDebug("用户名验证通过，开始生成JWT Token，用户: {UserName}", login.UserName);

                JwtTokenModel tokenModel = new JwtTokenModel()
                {
                    Uid = 1,
                    UserName = login.UserName,
                    Role = "Admin",
                };

                string jwtToken = JwtHelper.IssueJwt(tokenModel);
                
                _logger.LogInformation("JWT Token生成成功，用户: {UserName}, 角色: {Role}", 
                    login.UserName, tokenModel.Role);

                TokenResult result = new TokenResult()
                {
                    Token = jwtToken,
                    TokenType = "Bearer"
                };
                
                _logger.LogDebug("返回JWT Token结果，Token长度: {TokenLength}", jwtToken?.Length ?? 0);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成JWT Token时发生错误，用户名: {UserName}", login?.UserName ?? "未知");
                return StatusCode(500, "服务器内部错误");
            }
        }
    }
}
